package com.cxb.carrecorder;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.cxb.carrecorder.PreviewService.DeleteFileService;

import java.io.File;
import java.util.*;

public class VideoListActivity extends Activity {
	private ListView listView = null;
	private List<File> fileList = null;
	int mPositon;
	private boolean isLockDir;
	private VideoListAdapter videoListAdapter;
	
	private TextView mTitleView = null;
	private TextView mSelectView = null;
	private ImageView mDeleteView = null;
	private TextView mSelectAllView = null;
	private TextView mCancelView = null;
	//added by huqingkui
	TextView mTVIsEmpty;
	private boolean mIsSelect = false;
	
	private DeleteFileService mService = null;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == 20003)
			{
				Log.d("pumkid", "20003");
				if(videoListAdapter!=null)
					videoListAdapter.notifyDataSetChanged();
			}
		}
	};
	
	class BitmapThread extends AsyncTask<ArrayList<String>, Object, Object>{
		public ArrayList<String> imgUrls = new ArrayList<String>();
		
		public void putUrl(String url)
		{
			synchronized (imgUrls) {
				imgUrls.add(url);
			}
		}
		
		public void putUrls(ArrayList<String> urls)
		{
			synchronized (imgUrls) {
				imgUrls = urls;
			}
		}
		
		public void finishGetting(String url)
		{
			synchronized (imgUrls) {
				imgUrls.remove(url);
			}
		}
		
		public String getUrl()
		{
			synchronized (imgUrls) {
				if(imgUrls != null && imgUrls.size() > 0)
				{
					return imgUrls.get(0);
				}
			}
			return null;
		}
		
		
		public void run()
		{
			String url = null;
			while(!TextUtils.isEmpty((url = getUrl())))
			{
				Log.d("pumkid", "url "+url);
				VideoRecorder.getVideoThumbnailFile(url);
				finishGetting(url);
				handler.sendEmptyMessage(20003);
			}
			
		}

		private boolean isRunning = false;
		
		public boolean isRunning()
		{
			return isRunning;
		}
		
		
		
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			isRunning = false;
		}

		@Override
		protected Object doInBackground(ArrayList<String>... params) {
			isRunning = true;
				putUrls(params[0]);
				run();
			
			return null;
		}
	};
	BitmapThread  bitmapGetter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.filelist_activity);
		
		listView = (ListView) this.findViewById(R.id.filelist);
		File videoPath = new File(VideoRecorder.VIDEOS_PATH_NORMAL);

		isLockDir = getIntent().getBooleanExtra("isLock", false);

		//added by huqingkui
		mTVIsEmpty = (TextView) findViewById(R.id.tv_isempty);
//		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
//			@Override
//			public boolean onItemLongClick(AdapterView<?> adapterView,
//					View view, int position, long id) {
//
//				final File file = new File(view.getTag().toString());
//				if (file.isFile()) {
//					String[] menu = null;
//
//					if (!isLockDir) {
//
//						menu = new String[] { getString(R.string.lock_file),
//								getString(R.string.delete),
//								getString(R.string.cancel), };
//					} else {
//						menu = new String[] { getString(R.string.delete),
//								getString(R.string.cancel) };
//					}
//					Builder build = new AlertDialog.Builder(
//							VideoListActivity.this);
//					build.setItems(menu, new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							if (isLockDir) {
//								which++;
//							}
//							if (which == 0) {
//								// ����¼���ļ�
//								lockFile(file.getAbsolutePath());
//							} else if (which == 1) {
//								AlertDialog.Builder builder = new AlertDialog.Builder(
//										VideoListActivity.this);
//								builder.setTitle(getString(R.string.worning));
//								builder.setMessage(getString(R.string.deleteverify));
//								builder.setPositiveButton(
//										getString(R.string.ok),
//										new DialogInterface.OnClickListener() {
//											@Override
//											public void onClick(
//													DialogInterface dialog,
//													int which) {
//
//												deleteFiles(file);
//											}
//										});
//
//								builder.setNegativeButton(
//										getString(R.string.cancel),
//										new DialogInterface.OnClickListener() {
//											@Override
//											public void onClick(
//													DialogInterface dialog,
//													int which) {
//												dialog.cancel();
//											}
//										});
//								builder.create().show();
//							} else if (which == 2) {
//								dialog.cancel();
//							}
//						}
//					});
//					build.show();
//				}
//				return true;
//			}
//		});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				final String path = view.getTag().toString();
				if(mIsSelect)
				{
					if(videoListAdapter.getItemState(position) == 1)
						videoListAdapter.SelectItem(position, 0);
					else
						videoListAdapter.SelectItem(position, 1);
				}
				else if (fileList.get(position).isFile()) {
					Intent intent = new Intent();
					intent.putExtra("path", path);
					// intent.putExtra("file_position",
					// mPositon);
					intent.putExtra("dir_path",
					fileList.get(mPositon).getParent());
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setClass(getApplicationContext(),
					PlayerActivity.class);
					startActivity(intent);
				}
			}
		});
		
		mTitleView = (TextView) findViewById(R.id.filelist_title);
		if(isLockDir)
			mTitleView.setText(R.string.lock_folder);
		else
			mTitleView.setText(R.string.temp_folder);
		
		mSelectView = (TextView) findViewById(R.id.filelist_select);
		mSelectView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateSelectState();
			}
		});
		mSelectView.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN)
				{
					mSelectView.setTextColor(getResources().getColor(R.color.text_blue));
					
				}
				else if(event.getAction() == MotionEvent.ACTION_UP)
				{
					mSelectView.setTextColor(getResources().getColor(R.color.text_gray));
				}
				return false;
			}
			
		});
		
		mDeleteView = (ImageView) findViewById(R.id.filelist_delete);
		mDeleteView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(videoListAdapter.IsSelected() == false) return;
				
				final AlertDialog deleteDialog = new AlertDialog.Builder(VideoListActivity.this).create();  
        		deleteDialog.show();   
        		deleteDialog.getWindow().setContentView(R.layout.delete_dialog);  
        		deleteDialog.getWindow()  
        		.findViewById(R.id.cancel_button)  
        		.setOnClickListener(new View.OnClickListener() {  
        			//@Override  
        			public void onClick(View v) {
        				deleteDialog.dismiss();  
        			}  
        		});  
        		deleteDialog.getWindow()  
        		.findViewById(R.id.delete_button)  
        		.setOnClickListener(new View.OnClickListener() {  
        			//@Override  
        			public void onClick(View v) {  
        				for(int i = videoListAdapter.mSelFileList.size() - 1; i >= 0; i--)
        				{
        					if(videoListAdapter.mSelFileList.get(i) == 1)
        					{
        						//int size = fileList.size();
        						deleteFiles(fileList.get(i)); 
        						fileList.remove(i);
        						videoListAdapter.mSelFileList.remove(i);
        						videoListAdapter.listItems.remove(i);
        					}
        				}


        				videoListAdapter.UpdateItem();
        				deleteDialog.dismiss();

						//added by huqingkui 当全部删除掉时隐藏一些控件
						if(videoListAdapter.listItems.size() <= 0){
							mDeleteView.setVisibility(View.GONE);
							mCancelView.setVisibility(View.GONE);
							mSelectView.setVisibility(View.GONE);
							mSelectAllView.setVisibility(View.GONE);

							mTVIsEmpty.setVisibility(View.VISIBLE);
						}
        			}  
        		});  
			}
		});	
				
		mSelectAllView = (TextView) findViewById(R.id.filelist_select_all);
		mSelectAllView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				videoListAdapter.SelectAllItem(1);
			}
		});	
		mSelectAllView.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN)
				{
					mSelectAllView.setTextColor(getResources().getColor(R.color.text_blue));
					
				}
				else if(event.getAction() == MotionEvent.ACTION_UP)
				{
					mSelectAllView.setTextColor(getResources().getColor(R.color.text_gray));
				}
				return false;
			}
			
		});
		
		mCancelView = (TextView) findViewById(R.id.filelist_cancel);
		mCancelView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				videoListAdapter.SelectAllItem(0);
				updateSelectState();
			}
		});	
		mCancelView.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN)
				{
					mCancelView.setTextColor(getResources().getColor(R.color.text_blue));
					
				}
				else if(event.getAction() == MotionEvent.ACTION_UP)
				{
					mCancelView.setTextColor(getResources().getColor(R.color.text_gray));
				}
				return false;
			}
			
		});
		
		View returnButton = findViewById(R.id.return_button);
		returnButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
	}
	
	 @Override  
	 protected void onStart() {  
	 	super.onStart();  
	 	doBindService();  
	}  
	  
	 @Override  
	 	protected void onStop() {  
	        super.onStop();  
	        doUnbindService();  
	    }  
	private void updateSelectState()
	{
		mIsSelect = !mIsSelect;
		if(mIsSelect)
		{
			mDeleteView.setVisibility(View.VISIBLE);
			mSelectAllView.setVisibility(View.VISIBLE);
			mCancelView.setVisibility(View.VISIBLE);
			mSelectView.setVisibility(View.GONE);
		}
		else
		{
			mDeleteView.setVisibility(View.GONE);
			mSelectAllView.setVisibility(View.GONE);
			mCancelView.setVisibility(View.GONE);
			mSelectView.setVisibility(View.VISIBLE);
		}
	}
	
	private void lockFile(String path) {

		// 1.�ж��������ļ���

		File lockDir = new File(VideoRecorder.VIDEOS_PATH_LOCKED);
		if (lockDir.exists()) {
			File[] lockedFiles = lockDir.listFiles();
			if (lockedFiles != null && lockedFiles.length >= 5) {
				Utils.playTts(this,
						getString(R.string.lock_file_fail_too_more), true);
				return;
			}
		} else {
			lockDir.mkdirs();
		}
		// 2.�жϿռ�
		// 3.����������ʾ

		String szLockFile = VideoRecorder.VIDEOS_PATH_LOCKED
				+ path.substring(path.lastIndexOf(File.separator)
						+ File.separator.length());
		File file = new File(path);
		file.renameTo(new File(szLockFile));
		Utils.playTts(this, getString(R.string.lock_success), true);

		updateData();
	}

	private List<File> getVideoFiles(boolean isLockFile) {

		List<File> addFiles = new ArrayList<File>();

		File file = null;
		if (isLockFile) {
			file = new File(VideoRecorder.VIDEOS_PATH_LOCKED);
		} else {

			file = new File(VideoRecorder.VIDEOS_PATH_NORMAL);
		}

		File[] VideoFiles = file.listFiles();

		if (VideoFiles != null) {
			for (File norFile : VideoFiles) {
				if (norFile.getName().endsWith("3gp")) {
					addFiles.add(norFile);
				}
			}
		}

		Collections.sort(addFiles, new Comparator<File>() {

			@Override
			public int compare(File lhs, File rhs) {
				if (lhs.lastModified() > rhs.lastModified()) {
					return -1;
				} else if (lhs.lastModified() < rhs.lastModified()) {
					return 1;
				}
				return 0;
			}
		});

		return addFiles;
	}

	private void deleteFiles(File file) {
		file.delete();
	}

	private void deleteAllFiles() {
		fileList = getVideoFiles(isLockDir);
		if (fileList != null) {
			for (File video : fileList) {
				video.delete();
			}
		}
		
		Toast.makeText(this, R.string.delete_success, Toast.LENGTH_SHORT).show();
		updateData();
	}

	@Override
	protected void onResume() {
		updateData();
		super.onResume();
	}

	public void updateData() {
		File videoPath = null;
		if (isLockDir) {
			videoPath = new File(PreviewService.recorder.VIDEOS_PATH_LOCKED);
		} else {
			videoPath = new File(PreviewService.recorder.VIDEOS_PATH_NORMAL);

		}
		fileList = getVideoFiles(isLockDir);

		if (fileList.size() > 0) {
			inflateListView(fileList);
			listView.setVisibility(View.VISIBLE);

			////added by huqingkui  当列表不为空时要显示选择按钮
			mSelectView.setVisibility(View.VISIBLE);
			mTVIsEmpty.setVisibility(View.GONE);
		} else {
			listView.setVisibility(View.GONE);
			////added by huqingkui  当列表为空时不要显示选择按钮
			mSelectView.setVisibility(View.INVISIBLE);
			mTVIsEmpty.setVisibility(View.VISIBLE);
		}
	}

	private void inflateListView(List<File> files) {
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < files.size(); i++) {
			Map<String, Object> listItem = new HashMap<String, Object>();
			if (files.get(i).isDirectory()) {
				// listItem.put("icon", R.drawable.folder);//��ʾ�ļ��е�ͼƬ
				continue;
			} else {
				//listItem.put("icon", R.drawable.cr_unlock);// //��ʾ�ļ���ͼƬ
//				String thumbFile = VideoRecorder.getThumbnailFileName(files.get(i).getAbsolutePath());
//				if(!VideoRecorder.isFileExist(thumbFile))
//				{
//					if(VideoRecorder.getVideoThumbnailFile(files.get(i).getAbsolutePath()) == null)
//					{
//						 continue;
//					}
//				}
//				Bitmap thumbBitmap = BitmapFactory.decodeFile(thumbFile, null);
//				listItem.put("icon", thumbBitmap);// //��ʾ�ļ���ͼƬ
			}

			listItem.put("filename", files.get(i).getName());
			listItem.put("path", files.get(i).getAbsolutePath());

			listItems.add(listItem);
		}
			videoListAdapter = new VideoListAdapter(this, listItems);
			listView.setAdapter(videoListAdapter);
			
			if(files != null)
			{
				ArrayList<String> urls = new ArrayList<String>();
				for(int  i = 0; i < files.size() ; i++)
				{
					if(files.get(i).getAbsolutePath().endsWith(".3gp"))
					{
						urls.add(files.get(i).getAbsolutePath());
					}
				}
				bitmapGetter = new BitmapThread();
				bitmapGetter.execute(urls);
			}
		
	}

	class VideoListAdapter extends BaseAdapter {
		public List<Map<String, Object>> listItems;
		public List<String> liststrItems;
		public ArrayList<Integer> mSelFileList = null; 
		
		private Context mContext = null;

		public VideoListAdapter(Context context, List<Map<String, Object>> listItems) {
			this.listItems = listItems;
			mContext = context;
			mSelFileList = new ArrayList<Integer>();
	        for(int i = 0; i < getCount(); i++)
	        	mSelFileList.add(0);
		}
		

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listItems.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return listItems.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		private Bitmap getBitMap(String url)
		{
			url = VideoRecorder.getThumbnailFileName(url);
			File bitFile = new File(url);
			Bitmap thumbBitmap = null;
			if(bitFile.exists())
			{
				thumbBitmap = BitmapFactory.decodeFile(url, null);
			}
			return thumbBitmap;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(VideoListActivity.this)
						.inflate(R.layout.list_item, null);
			}
			Map<String, Object> map = (Map<String, Object>) getItem(position); 
			Bitmap srcBmp = null;
	        Bitmap selBmp = null;
	        Bitmap newBmp = null;
	        Bitmap lockBmp = null;
			ImageView iv = (ImageView) convertView.findViewById(R.id.icon);
			TextView tv = (TextView) convertView.findViewById(R.id.file_name);
			//iv.setImageResource((Integer) map.get("icon"));
//			if(liststrItems == null)
//				srcBmp = (Bitmap) this.listItems.get(position).get("icon");
//			else
			Log.d("pumkid", "path"+(String)map.get("path"));
			srcBmp = getBitMap((String)map.get("path"));
			
			if(srcBmp != null)
			{
				Log.d("pumkid", "path"+(String)map.get("path"));
				newBmp = Bitmap.createBitmap(srcBmp.getWidth(), srcBmp.getHeight(), Bitmap.Config.RGB_565);  
		        Canvas canvas = new Canvas(newBmp); 
		        Paint paint = new Paint();
		        canvas.drawBitmap(srcBmp, 0, 0, paint);  
		        
				if(isLockDir)
				{
					 lockBmp = ((BitmapDrawable)this.
			        			mContext.getResources().getDrawable(R.drawable.lock)).getBitmap(); 
				     canvas.drawBitmap(lockBmp, 
				    		 (srcBmp.getWidth() - lockBmp.getWidth()) - 5, 
				    		 (srcBmp.getHeight() - lockBmp.getHeight()) -5, 
				    		 paint);
			              
				}
				
				if((mSelFileList.size() > 0) && (mSelFileList.get(position) == 1)) {
		        	selBmp = ((BitmapDrawable)this.
		        			mContext.getResources().getDrawable(R.drawable.select)).getBitmap(); 
		        	canvas.drawBitmap(selBmp, 
		        			(srcBmp.getWidth() - selBmp.getWidth()) / 2, 
		        			(srcBmp.getHeight() - selBmp.getHeight()) / 2, paint);
		        }
		        
				canvas.save(Canvas.ALL_SAVE_FLAG);   
				iv.setImageBitmap(newBmp); 
				paint = null;
				canvas = null;
			}
	        tv.setText((CharSequence) map.get("filename"));
			convertView.setTag(map.get("path"));
			
			
			lockBmp = null;
			srcBmp = null;
	        selBmp = null;
	        newBmp = null;
			return convertView;
		}

		private void recycleBitmap(Bitmap bmp)
		{
			if((bmp != null) && (!bmp.isRecycled()))
			{
				bmp.recycle();
				bmp = null;
			}
		}
		
		public void SelectAllItem(int selectState)
		{
			for(int i = 0; i < mSelFileList.size(); i++)
				mSelFileList.set(i, selectState);
			notifyDataSetChanged();
		}
		
		public void SelectItem(int pos, int selectState)
		{
			mSelFileList.set(pos, selectState);
			notifyDataSetChanged();
		}
		
		public int getItemState(int pos)
		{
			return mSelFileList.get(pos);
		}
		
		public boolean IsSelected()
		{
			for(int i = 0; i < mSelFileList.size(); i++)
				if(mSelFileList.get(i) == 1)
					return true;
			return false;
		}
		
		public void RemoveSelectedItem()
		{
			notifyDataSetChanged();
		}
		
		public void UpdateItem()
		{
			notifyDataSetChanged();
		}
		
	}
	
	
	private void doBindService() {  
		Intent intent = new Intent(this, PreviewService.class);  
		boolean ret = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}  
 
    private void doUnbindService() {  
        if (mService != null) {  
            unbindService(mConnection);  
        }  
    }  
    
    private final IDeleteFile mDeleteFileCallBack = new IDeleteFile(){

		@Override
		public void onDeleteFile() {
			// TODO Auto-generated method stub
			videoListAdapter.UpdateItem();
		}
    	
    };

	private ServiceConnection mConnection = new ServiceConnection() {  
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			// TODO Auto-generated method stub
			mService = (DeleteFileService)arg1; 
			mService.setDeleteFileCallBack(mDeleteFileCallBack);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			// TODO Auto-generated method stub
			mService = null;  
		}  
    };  
}